<template>
    <el-dialog
    :close-on-click-modal="false"
    :title="title" top="2vh" :visible.sync="show" append-to-body
    width="80%">
    <div class="wp-order-create">
        <el-form :model="returnOrderInfo" ref="returnOrderRef" label-width="120px" :rules="rules">
            <el-row>
              <el-col :span="12">
                <el-form-item label="退货类型" prop="returnType">
                    <el-select  class="wp-form-280" @change="selectReturnType"  v-model="returnOrderInfo.returnType"  placeholder="请选择">
                    <el-option v-for="(item,index) in $parent.returnTypes" :key="index" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                  <el-form-item label="商定退货日期" prop="returnDate">
                    <el-date-picker
                    style="width:280px"
                    v-model="returnOrderInfo.returnDate"
                    type="date"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="选择日期时间">
                    </el-date-picker>
                  </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                  <el-form-item :label="returnOrderOption.label" prop="relationOrderNo" :rules="{ required: true, message: '不能为空', trigger: 'blur' }">
                     <PopoverSearch   @hide="onSelectOrder" ref="relationOrderNoRef" clearable :type="returnOrderOption.type" :placeholder="returnOrderOption.placeholder"  v-model="returnOrderInfo.relationOrderNo"  :lableKey="returnOrderOption.lableKey" :valueKey="returnOrderOption.valueKey"/>
                  </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="'退货'+returnOrderOption.relationNameLabel">
                  <el-input  disabled class="wp-form-280" v-model="returnOrderInfo.relationName" :placeholder="returnOrderOption.relationNameLabel"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                  <el-form-item  label="退款总金额" prop="returnTotalAmount" :rules="{ required: returnOrderInfo.returnType!==0, message: '不能为空', trigger: 'blur' }">
                        <el-input  :disabled="returnOrderInfo.returnType==0" class="wp-form-280" clearable v-model="returnOrderInfo.returnTotalAmount" placeholder="退款总金额"></el-input>
                  </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="负责人" prop="chargePerson">
                          <Employee-seach   :employeeCode.sync="returnOrderInfo.chargePerson" :employeeName.sync="returnOrderInfo.chargePersonName"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="备注" prop="remark">
                    <el-input
                        type="textarea"
                        class="wp-form-280"
                        v-model="returnOrderInfo.remark"
                        placeholder="备注"
                    ></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
             <div v-if="returnOrderInfo.returnType!==1">
              <el-collapse  :value="'2'">
              <el-collapse-item title="退货地址" name="2">
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" :rules="{ required: true, message: '不能为空', trigger: 'blur' }" :prop="this.returnOrderOption.type=='salesOrder'?'returnContractsCode':'returnContractsName'">
            <PopoverSearch
            v-if="this.returnOrderOption.type=='salesOrder'"
           :showMoreBtn="false" ref="contractsRef"  @hide="selectContracts"  placeholder="+添加联系人" type='customerSigner' :params="{customerCode:returnOrderInfo.relationCode}"  :disabled="!(returnOrderInfo.relationOrderNo && returnOrderInfo.relationOrderNo!==null)"   v-model="returnOrderInfo.returnContractsCode" valueKey="contactsCode" lableKey="contactsName"
           :name.sync="returnOrderInfo.returnContractsName"/>
             <el-input v-else  class="wp-form-280" v-model="returnOrderInfo.returnContractsName" placeholder="联系人"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="returnAddress" :rules="{ required: true, message: '不能为空', trigger: 'blur' }">
              <el-input
                class="wp-form-280"
                v-model="returnOrderInfo.returnAddress"
                placeholder="地址"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="returnContractsMobile" :rules="{ required: true, message: '不能为空', trigger: 'blur' }">
              <el-input
                class="wp-form-280"
                v-model="returnOrderInfo.returnContractsMobile"
                placeholder="手机号码"
                maxlength="11"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="returnContractsEmail">
              <el-input
                class="wp-form-280"
                v-model="returnOrderInfo.returnContractsEmail"
                placeholder="电子邮箱"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
       </el-collapse-item>
              </el-collapse>
            <div style="text-align:right;margin:5px 0">
                <el-button type="warning" @click="toOrderDetail">选择退货产品</el-button>
            </div>
            <el-table  show-summary      class="wp-product-table" :summary-method="getSummaries" :data="returnProductList">
                <el-table-column label="产品名称" prop="productName"></el-table-column>
                <el-table-column label="产品类型" prop="productTypeName"></el-table-column>
                <el-table-column label="产品型号"  prop="productModel"></el-table-column>
                <el-table-column label="产品单位" prop="unit"></el-table-column>
                <el-table-column :label="returnOrderOption.productLabel+'数量'" prop="productNum"></el-table-column>
                <el-table-column :label="returnOrderOption.productLabel+'金额'" prop="discountTotalAmount"></el-table-column>
                <el-table-column label="退货数量"  width="150" prop="returnNum">
                    <template slot-scope="scope">
                      <el-input-number size="mini" :min="1" :max="scope['row']['productNum']" v-model="scope.row.returnNum"  placeholder="请填写"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column  label="退款金额" width="150" prop="returnAmount">
                   <template slot-scope="scope">
                      <el-input-number :disabled="returnOrderInfo.returnType!==2" size="mini" :min="0"   v-model="scope.row.returnAmount"  placeholder="请填写"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column  label="退货原因"  width="150" prop="returnReason">
                    <template slot-scope="scope">
                        <el-input  v-model="scope.row.returnReason" placeholder="填写退货原因"></el-input>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" align="center" label="操作">
                     <template slot-scope="scope">
                         <el-link type="danger" @click="deleteReturnProduct(scope.$index,scope.row)" >删 除</el-link>
                     </template>
                </el-table-column>
            </el-table>
            </div>
        </el-form>
    </div>
        <el-dialog  append-to-body :title="returnOrderOption.label+'产品信息'" :visible.sync="visibleOrderDetail">
            <el-table :data="orderDetailList" ref="returnProductRef">
              <el-table-column type="selection"  :selectable="checkSelect" width="50"></el-table-column>
              <el-table-column label="产品名称" show-overflow-tooltip prop="productName"></el-table-column>
              <el-table-column label="产品类型" prop="productTypeName"></el-table-column>
              <el-table-column label="产品型号"  show-overflow-tooltip prop="productModel"></el-table-column>
              <el-table-column label="产品单位" prop="unit"></el-table-column>
              <el-table-column :label="returnOrderOption.productLabel+'数量'" :prop="returnOrderOption.productNumKey"></el-table-column>
              <el-table-column :label="returnOrderOption.productLabel+'金额'" prop="discountTotalAmount"></el-table-column>
            </el-table>
             <div slot="footer" class="wp-footer__box">
                <el-button type="" @click="visibleOrderDetail=false">取消</el-button>
                <el-button type="success" @click="selectReturnProduct">确定</el-button>
            </div>
        </el-dialog>
        <div slot="footer" class="wp-footer__box">
            <el-button @click.native="show=false">取消</el-button>
            <el-button
                type="warning"
                @click.native="save(1)"
                >保存提交</el-button>
                    <el-button
                type="success"
                @click.native="save(0)"
                >保存草稿</el-button>
        </div>
    </el-dialog>
</template>
<script>
import PopoverSearch from '@/views/components/popoverSearch'
import EmployeeSeach from '@/views/components/EmployeeSeach'
import purchaseOrder from '@/api/eims/purchase/orderAPI'
import salesOrder from '@/api/eims/sales/salesOrderAPI'
import returnOrder from '@/api/eims/returnOrderAPI'
import {toDecimal} from '@/utils'
export default {
  props: {
    title: String,
    type: String,
    visible: {type: false, default: false}
  },
  components: {PopoverSearch, EmployeeSeach},
  computed: {
    returnOrderOption () {
      const option = {}
      if (this.type === 'purchaseOrder') {
        option.lableKey = 'purchaseNo'
        option.valueKey = 'purchaseNo'
        option.type = 'purchaseOrder'
        option.placeholder = '+添加采购订单'
        option.label = '采购订单'
        option.productLabel = '采购'
        option.productNumKey = 'purchaseNum'
        option.relationNameKey = 'supplierName'
        option.relationCodeKey = 'supplierCode'
        option.relationDetailNoKey = 'purchaseDetailNo'
        option.relationNameLabel = '经销商'
        option.queryProductFun = (orderNo, cb) => {
          this.getPurchaseOrderDetialList(orderNo, cb)
        }
      } else {
        option.lableKey = 'orderNo'
        option.valueKey = 'orderNo'
        option.type = 'salesOrder'
        option.placeholder = '+添加销售订单'
        option.label = '销售订单'
        option.productLabel = '销售'
        option.productNumKey = 'productNum'
        option.relationNameKey = 'customerName'
        option.relationCodeKey = 'customerCode'
        option.relationDetailNoKey = 'orderDetailNo'
        option.relationNameLabel = '客户'
        option.queryProductFun = (orderNo, cb) => {
          this.getSalesOrderProductList(orderNo, cb)
        }
      }
      return option
    },
    show: {
      get () {
        return this.visible
      },
      set (val) {
        this.init()
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    totalSumAmount: {
      handler (val) {
        this.$set(this.returnOrderInfo, 'returnTotalAmount', val)
      }
    }
  },
  data () {
    return {
      visibleOrderDetail: false,
      orderDetailList: [],
      returnProductList: [],
      totalSumAmount: null,
      returnOrderInfo: {
        returnType: 2
      },
      rules: {
        returnType: [{ required: true, message: '不能为空', trigger: 'blur' }],
        chargePerson: [{ required: true, message: '不能为空', trigger: 'blur' }],
        returnDate: [{ required: true, message: '不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    init () {
      this.returnOrderInfo = {
        returnType: 2
      }
      this.orderDetailList = []
      this.returnProductList = []
      this.$refs.relationOrderNoRef.inputClear()
      if (this.$refs.contractsRef) {
        this.$refs.contractsRef.inputClear()
      }
    },
    selectReturnType (val) {
      if (val === 0) {
        this.totalSumAmount = null
        this.returnProductList.forEach(item => {
          item.returnAmount = null
        })
      }
    },
    onSelectOrder (data) {
      this.orderDetailList = []
      this.returnProductList = []
      this.$set(this.returnOrderInfo, 'relationName', data[this.returnOrderOption.relationNameKey])
      this.$set(this.returnOrderInfo, 'relationCode', data[this.returnOrderOption.relationCodeKey])
      if (this.returnOrderOption.type === 'purchaseOrder') {
        // this.$set(this.returnOrderInfo, 'returnAddress', data.address)
        // this.$set(this.returnOrderInfo, 'returnContactsEmail', data.email)
        // this.$set(this.returnOrderInfo, 'returnContractsMobile', data.contactsMobile)
      }
    },
    selectContracts (data) {
      this.$set(this.returnOrderInfo, 'returnAddress', data.address)
      this.$set(this.returnOrderInfo, 'returnContactsEmail', data.email)
      this.$set(this.returnOrderInfo, 'returnContractsMobile', data.mobile)
    },
    toOrderDetail () {
      if (!this.returnOrderInfo.relationOrderNo) {
        this.$msgBox.error(`请选择${this.returnOrderOption.label}`)
        return
      }
      this.visibleOrderDetail = true
      this.returnOrderOption.queryProductFun(this.returnOrderInfo.relationOrderNo, res => {
        this.orderDetailList = res.data || []
      })
    },
    checkSelect (row, index) {
      if (this.returnProductList) {
        const productInfo = this.returnProductList.find(item => {
          return item.productCode === row.productCode
        })
        return (
          !productInfo || Object.getOwnPropertyNames(productInfo).length === 0
        )
      }
      return true
    },
    selectReturnProduct () {
      const returnProduct = this.$refs.returnProductRef.selection
      if (!returnProduct || returnProduct.length <= 0) {
        this.$msgBox.error(`请选择退货产品`)
        return
      }
      const selectReturnProductList = returnProduct.map(item => {
        const productInfo = {}
        productInfo.discountTotalAmount = item.discountTotalAmount
        productInfo.productCode = item.productCode
        productInfo.productName = item.productName
        productInfo.productTypeName = item.productTypeName
        productInfo.productType = item.productType
        productInfo.productModel = item.productModel
        productInfo.unit = item.unit
        productInfo.relationDetailNo = item[this.returnOrderOption.relationDetailNoKey]
        productInfo.productNum = item[this.returnOrderOption.productNumKey]
        return productInfo
      })
      this.returnProductList = [...selectReturnProductList, ...this.returnProductList]
      this.$refs.returnProductRef.clearSelection()
      this.visibleOrderDetail = false
    },
    deleteReturnProduct (index, row) {
      this.$msgBox.confirm(
        '确认删除退款产品' + (row.productName || '') + '?',
        () => {
          this.returnProductList.splice(index, 1)
        }
      )
    },
    getPurchaseOrderDetialList (orderNo, cb) {
      purchaseOrder.getOrderProductListAPI(orderNo).then(res => {
        cb(res)
      })
    },
    getSalesOrderProductList (orderNo, cb) {
      salesOrder.getOrderProductListAPI(orderNo).then(res => {
        cb(res)
      })
    },
    getSummaries (param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = ''
          return
        }
        const values = data.map((item) => Number(item[column.property]))
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = Math.round(sums[index] * 100) / 100
        }
      })
      this.totalSumAmount = toDecimal(sums[7]||0)
      return sums
    },
    checkProduct () {
      if (this.returnProductList && this.returnProductList.length > 0) {
        const info = this.returnProductList.find(item => {
          return !item.returnNum || item.returnNum <= 0
        })
        if (info) {
          this.$msgBox.error('请填写产品退货数量')
          return false
        }
      } else {
        if (this.returnOrderInfo.returnType === 0 || this.returnOrderInfo.returnType === 2) {
          this.$msgBox.error('请选择退货产品')
          return false
        }
      }
      return true
    },
    save (status) {
      this.$refs.returnOrderRef.validate((valid) => {
        if (valid && this.checkProduct()) {
          const params = {...this.returnOrderInfo}
          params.status = status
          params.returnOrderType = this.type === 'purchaseOrder' ? 1 : 0
          params.orderReturnDetailInfoList = this.returnProductList
          returnOrder.saveReturnOrderInfoAPI(params).then(res => {
            if (res.code === 0) {
              this.show = false
              this.$emit('afterSave', res)
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.wp-order-create {
  max-height: 410px;
  overflow: auto;
  padding: 10px;
}
.wp-product-table >>> .el-table__footer-wrapper,
.wp-product-table >>> .el-table__footer {
  display: none;
}
</style>
